/* eslint-disable */

import indexConfig from '@/config/index.config';
import {
// 支付宝h5支付
	toaliwappay ,
// 获取微信公众号支付
	wechatofficialaccountpayparm ,
// 获取微信H5支付参数
	wechath5payparm ,recharge_toalipagepay,recharge_wechatqrpayparm
} from '@/api/basic';
// #ifdef H5
import jweixin from '@/common/jweixin';
// #endif
import {querybaseinfoset,
	//APP支付宝支付
	aliPay ,
// 支付宝pc支付
	toalipagepay ,
// 获取微信小程序支付
	wechatappletpay ,
// APP微信支付
	wxpay} from '@/api/basic';
import {isBindingCheck,getJsapiTicket} from '@/api/login';
import {http} from '@/utils/request';
import mHelper from '@/utils/helper';
import mRouter from '@/utils/router';
import {toprepay,} from '@/api/product';


export default {
	// 判断是否公众号（微信H5）
	isWechat() {
		// #ifdef H5
		const ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == 'micromessenger') {
			return true;
		} else {
			return false;
		}
		// #endif
	},

	// wxjssdk
	async wxConfigH5(url) {
		if (this.isWechat()) {
			const jsApiList = JSON.stringify([
				'chooseWXPay',
				'scanQRCode',
				'updateAppMessageShareData', 'onMenuShareQQ','getLocation',
				'updateTimelineShareData','onMenuShareQZone'
			]);
			await http
				.get(`${getJsapiTicket}`, {
					url: url,
					jsApiList, // 需要调用微信的原生方法
					debug: true // 是否打开调试
				})
				.then(result => {
					jweixin.config({
						debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
						appId:result.appId, // 必填，公众号的唯一标识
						timestamp: result.timestamp, // 必填，生成签名的时间戳
						nonceStr: result.nonceStr, // 必填，生成签名的随机串
						signature: result.signature,// 必填，签名
						jsApiList: ['chooseWXPay',
							'scanQRCode',"onMenuShareTimeline",'updateAppMessageShareData', 'onMenuShareQQ','getLocation',
							'updateTimelineShareData','onMenuShareQZone', "onMenuShareAppMessage", "onMenuShareWeibo", "chooseImage",
							"uploadImage", "hideMenuItems", "closeWindow"
						] // 所有要调用的 API 都要加到这个列表中
					});
					jweixin.ready(function () {
						// 在这里调用 API
						wx.hideMenuItems({
							menuList: ['menuItem:copyUrl', 'menuItem:favorite', 'menuItem:originPage', 'menuItem:openWithQQBrowser','menuItem:openWithSafari',
								'menuItem:share:email', 'menuItem:share:qq', 'menuItem:share:weiboApp','menuItem:share:QZone'
							] // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3,分享朋友：'menuItem:share:appMessage',分享朋友圈：'menuItem:share:timeline'
						});
						//获取“分享给朋友”按钮点击状态及自定义分享内容接口（即将废弃）
						jweixin.onMenuShareAppMessage({
							title: '快戳我啊！让您享受白菜价网购的快感', // 分享标题
							desc: '先领优惠券再下单享受折上折,各种大额优惠券让你领到手软呦！快戳我！快戳我！', // 分享描述
							link: 'https://mojin.51wangshi.com/pages/index/index', // 分享链接
							imgUrl: 'https://img-cdn-aliyun.dcloud.net.cn/stream/plugin_screens/4d9ccff0-65a0-11ea-b390-c5cb19d91445_1.png?v=1602645399', // 分享图标
							type: '', // 分享类型,music、video或link，不填默认为link
							dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
							success: function () {
								mHelper.toast('分享成功')
							}
						})
//获取“分享到朋友圈”按钮点击状态及自定义分享内容接口（即将废弃）
						jweixin.onMenuShareTimeline({
							title: '快戳我啊！让您享受白菜价网购的快感', // 分享标题
							desc: '先领优惠券再下单享受折上折,各种大额优惠券让你领到手软呦！快戳我！快戳我！', // 分享描述
							link: 'https://mojin.51wangshi.com/pages/index/index', // 分享链接
							imgUrl: 'https://img-cdn-aliyun.dcloud.net.cn/stream/plugin_screens/4d9ccff0-65a0-11ea-b390-c5cb19d91445_1.png?v=1602645399', // 分享图标
							type: '', // 分享类型,music、video或link，不填默认为link
							dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
							success: function () {
								mHelper.toast('分享成功')
							}
						})
					});
					});
		}
	},
	checkWXJSBridge(data) {
		let that = this
		let interval = setInterval(() => {
			if (typeof window.WeixinJSBridge != 'undefined') {
				clearTimeout(interval)
				that.onBridgeReady(data)
			}
		}, 200)
	},
	checkWXJSBridge1(data) {
		let that = this
		let interval = setInterval(() => {
			if (typeof window.WeixinJSBridge != 'undefined') {
				clearTimeout(interval)
				that.onBridgeReady1(data)
			}
		}, 200)
	},
	onBridgeReady1(data) {

		var _this = this
		window.WeixinJSBridge.invoke(
			'getBrandWCPayRequest', {
				appId: data.appid, // 公众号名称，由商户传入
				timeStamp: data.time_stamp, // 时间戳，自1970年以来的秒数
				nonceStr: data.nonce_str, // 随机串
				package: data.package_,
				signType: data.sign_type, // 微信签名方式：
				paySign: data.pay_sign // 微信签名
			},
			function(res) {


				if (res.err_msg === 'get_brand_wcpay_request:ok') {
					mHelper.toast('充值成功')
				} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
					mHelper.toast('取消充值')
				} else {
					mHelper.toast('充值失败')
				}
				setTimeout(() => {
					mRouter.push({
						route: '/pages/user/money/rechangeSucess?type=2&orderCode=' + data.result_code
					});

				}, 500)
			}
		)
	},
	onBridgeReady(data) {

		var _this = this
		window.WeixinJSBridge.invoke(
			'getBrandWCPayRequest', {
				appId: data.appid, // 公众号名称，由商户传入
				timeStamp: data.time_stamp, // 时间戳，自1970年以来的秒数
				nonceStr: data.nonce_str, // 随机串
				package: data.package_,
				signType: data.sign_type, // 微信签名方式：
				paySign: data.pay_sign // 微信签名
			},
			function(res) {


				if (res.err_msg === 'get_brand_wcpay_request:ok') {
					mHelper.toast('支付成功')
				} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
					mHelper.toast('取消支付')
				} else {
					mHelper.toast('支付失败')
				}
				setTimeout(() => {
					mRouter.push({
						route: '/pages/user/money/success??type=1&orderCode=' + data.result_code
					});

				}, 500)
			}
		)
	},
	/*
	 *@des 微信支付
	 *
	 *@param order_group 订单:order;充值:recharge;
	 *@param data 订单 {“order_id”:199} 充值 {“money”:100};
	 */
	async weixinPay(order_group, data, route = '/pages/user/money/success', code) {

		let url='';
		// #ifdef H5
		if (this.isWechat()) {//TODO
			url=`${wechatofficialaccountpayparm}`;
		}else{
			url=`${wechath5payparm}`;
		}
		// #endif
		// #ifdef APP-PLUS
		  url=`${wxpay}`;
		// #endif
		// #ifdef MP-WEIXIN
			url=`${wechatappletpay}`;
		// #endif

		// #ifdef APP-PLUS
		await http
			.get(url, {
				order_group,
				pay_type: 1,
				storeId:indexConfig.storeId,
				trade_type: 'app',
				data
			})
			.then(r => {
				uni.requestPayment({
					provider: 'wxpay', // 微信支付
					orderInfo: JSON.stringify(r.data), //微信订单数据 r.config
					success: function () {
						mHelper.toast('支付成功');
						mRouter.redirectTo({route});
					},
					fail: function (err) {

						mHelper.toast('支付已取消');
					}
				});
			});
		// #endif
		// #ifdef MP-WEIXIN
		await http
			.get(url, {
				order_group,
				pay_type: 1,
				trade_type: 'mini_program',
				orderCode:data.orderCode,
				storeId:indexConfig.storeId,
				orderId:data.orderId,
				orderType: data.orderType,
				type:data.type,
			})
			.then(r => {

				if(r.flag==-10){
					mHelper.toast('请绑定微信');
					mRouter.push({
						route: '/pages/public/auth'
					});
					return false;
				}
				if(r.flag==-5){
					mHelper.toast('微信生成预支付信息错误');
					return false;
				}
				if(r.flag==-3){
					mHelper.toast('没有待支付订单');
					return false;
				}
				if(r.flag==-9){
					mHelper.toast('没开启');
					return false;
				}
				if(r.flag==-8){
					mHelper.toast('参数错误');
					return false;
				}
				if(r.flag==-11){
					mHelper.toast('请绑定手机号');
					mRouter.push({
						route: '/pages/public/bindMobile'
					});
					return false;
				}
				uni.requestPayment({
					provider: 'wxpay',
					nonceStr: r.data.nonce_str,
					package: r.data.package_,
					signType: r.data.sign_type,
					paySign: r.data.pay_sign,
					timeStamp: r.data.time_stamp,
					success: () => {
						mHelper.toast('支付成功');
						mRouter.redirectTo({route});
					},
					fail: res => {
							mHelper.toast(res);

					},
					complete: () => {
					}
				});

			});
		// #endif
		// #ifdef H5
		await http
			.get(url, {
				order_group,
				pay_type: 1,
				trade_type: 'js',
				storeId:indexConfig.storeId,
				orderCode:data.orderCode,
				orderId:data.orderId,
				orderType: data.orderType,
				type:data.type,
				//	openid: res.data.openid
			})
			.then(r => {
				if(r.flag==-10){
					mHelper.toast('请绑定微信');
					mRouter.push({
						route: '/pages/public/auth'
					});
					return false;
				}
				if(r.flag==-5){
					mHelper.toast('微信生成预支付信息错误');
					return false;
				}
				if(r.flag==-3){
					mHelper.toast('没有待支付订单');
					return false;
				}
				if(r.flag==-9){
					mHelper.toast('没开启');
					return false;
				}
				if(r.flag==-8){
					mHelper.toast('参数错误');
					return false;
				}
				if(r.flag==-11){
					mHelper.toast('请绑定手机号');
					mRouter.push({
						route: '/pages/public/bindMobile'
					});
					return false;
				}
				if (this.isWechat()) {
					if (r) {
						this.checkWXJSBridge(r.data)
					}else{
						window.location.href = r.msg
						return;
					}
				}else{
					location.href=r.data.mwebUrl
				}

			});
		// #endif


	},


	/*
	 *@des 支付宝支付
	 *
	 *@param order_group 订单:order;充值:recharge;
	 *@param data 订单 {“order_id”:199} 充值 {“money”:100};
	 */
	async aliPay(order_group, data, route = '/pages/user/money/success') {

		// #ifdef MP-QQ
		mHelper.toast('QQ小程序不支持支付宝充值');
		return;
		// #endif
		// #ifdef MP-WEIXIN
		mHelper.toast('微信小程序不支持支付宝充值');
		return;
		// #endif

		let url='';
		// #ifdef H5
		url=`${toaliwappay}`;
			// #endif
			// #ifdef APP-PLUS
		url=`${aliPay}`;
			// #endif
		await http
			.get(url, {
				orderCode:data.orderCode,
				orderId:11,
				storeId:indexConfig.storeId,
				orderType: 1,
				type:data.type,
				// #ifdef H5
				trade_type: 'wap',
				// #endif
				// #ifdef APP-PLUS
				trade_type: 'app',
				// #endif

			})
			.then(r => {

				// #ifdef H5
				if (r) {
					let divDom = document.createElement('div')
					divDom.innerHTML = r.data;
					document.body.appendChild(divDom)

					let testForm = document.getElementsByName('punchout_form')
					testForm[0].dispatchEvent(new Event('submit'))
					testForm[0].submit()
					document.body.removeChild(testForm[0])

				}
			//	window.location.href = r;
				// #endif
				// #ifdef APP-PLUS
				uni.requestPayment({
					provider: 'alipay',
					orderInfo: r, //微信、支付宝订单数据
					success: function () {
						mHelper.toast('支付成功');
						mRouter.redirectTo({route});
					},
					fail: function (err) {

						mHelper.toast(err);
					}
				});
				// #endif
			});
	},

	/*
	 *@des 余额支付
	 *
	 *@param data 支付参数
	 */
	async balancePay(data, route = '/pages/set/pay/setPassword?type=1') {
		data.storeId=indexConfig.storeId;
		await http
			.post(`${toprepay}`, data)
			.then(r => {
				// -1:用户不存在 -2:支付密码错误 -3:没有待支付的订单 -4:用户预存款金额不足 -6:没有设置支付密码 1 成功
				if (-1 == r) {
					mHelper.toast('用户不存在');
				} else if (-2 == r) {
					mHelper.toast('支付密码错误');
				} else if (-3 == r) {
					mHelper.toast('没有待支付的订单');
				} else if (-4 == r) {
					mHelper.toast('用户预存款金额不足');
				} else if (-6 == r) {
					uni.showModal({
						content: '您尚未设置支付密码，是否跳转支付密码页面？',
						success: confirmRes => {
							if (confirmRes.confirm) {
								mRouter.push({ route: '/pages/set/pay/setPassword' });
							} else {
								this.btnLoading = false;
							}
						}
					});
				} else if (1 == r) {
					mRouter.redirectTo({route});
				}

			});
	},
	/*
	 *@des 微信支付
	 * type 1 公众号 2 h5 3 小程序 4 app 5 pc
	 *@param order_group 订单:order;充值:recharge;
	 *@param data 订单 {“order_id”:199} 充值 {“money”:100};
	 */
	async weixinRecharge(order_group, data, route = '/pages/user/money/success', code) {
		let url=`${recharge_wechatqrpayparm}`;
		let type=3;
		// #ifdef H5
		if (this.isWechat()) {//TODO
			type=1;
		}else{
			type=2;
		}
		// #endif
		// #ifdef APP-PLUS
		type=4;
		// #endif

		// #ifdef APP-PLUS
		await http
			.get(url, {
				order_group,
				type: type,
				storeId:indexConfig.storeId,
				money:data.money,
				trade_type: 'app',
				data
			})
			.then(r => {
				uni.requestPayment({
					provider: 'wxpay', // 微信支付
					orderInfo: JSON.stringify(r.data), //微信订单数据 r.config
					success: function () {
						mHelper.toast('支付成功');
						mRouter.redirectTo({route});
					},
					fail: function (err) {

						mHelper.toast(err);
					}
				});
			});
		// #endif
		// #ifdef MP-WEIXIN
		await http
			.get(url, {
				type: type,
				trade_type: 'mini_program',
				storeId:indexConfig.storeId,
				money:data.money

			})
			.then(r => {

				if(r.flag==-10){
					mHelper.toast('请绑定微信');
					mRouter.push({
						route: '/pages/public/auth'
					});
					return false;
				}
				if(r.flag==-5){
					mHelper.toast('微信生成预支付信息错误');
					return false;
				}
				if(r.flag==-11){
					mHelper.toast('请绑定手机号');
					mRouter.push({
						route: '/pages/public/bindMobile'
					});
					return false;
				}
				uni.requestPayment({
					provider: 'wxpay',
					nonceStr: r.nonce_str,
					package: r.package_,
					signType: r.sign_type,
					paySign: r.pay_sign,
					timeStamp: r.time_stamp,
					success: () => {
						mHelper.toast('支付成功');
						mRouter.redirectTo({route});
					},
					fail: res => {
						mHelper.toast(res);

					},
					complete: () => {
					}
				});

			});
		// #endif
		// #ifdef H5
		await http
			.get(url, {
				order_group,
				pay_type: 1,
				trade_type: 'js',
				money:data.money,
				storeId:indexConfig.storeId,
				orderCode:data.orderCode,
				orderId:data.orderId,
				orderType: data.orderType,
				type: type,
				//	openid: res.data.openid
			})
			.then(r => {
				if (this.isWechat()) {
					if (r) {
						this.checkWXJSBridge1(r)
					}else{
						window.location.href = r.msg
						return;
					}
				}else{
					location.href=r.data.mwebUrl
				}

			});
		// #endif


	},
	/*
  	 *@des 支付宝充值
  	 *
  	 *@param order_group 订单:order;充值:recharge;
  	 2 h5  4 app 5 pc
  	 *@param data 订单 {“order_id”:199} 充值 {“money”:100};
  	 */
  	async aliPayRecharge(order_group, data, route = '/pages/user/money/success') {

  		// #ifdef MP-QQ
  		mHelper.toast('QQ小程序不支持支付宝充值');
  		return;
  		// #endif
  		// #ifdef MP-WEIXIN
  		mHelper.toast('微信小程序不支持支付宝充值');
  		return;
  		// #endif
  	let type=2;
  		let url=`${recharge_toalipagepay}`;
  		// #ifdef H5
  		 type=2;
  			// #endif
  			// #ifdef APP-PLUS
  		 type=4;
  			// #endif
  		await http
  			.get(url, {
  				storeId:indexConfig.storeId,
  				money:data.money,
  				type:type,
  				// #ifdef H5
  				trade_type: 'wap',
  				// #endif
  				// #ifdef APP-PLUS
  				trade_type: 'app',
  				// #endif

  			})
  			.then(r => {

  				// #ifdef H5
  				if (r) {
  					let divDom = document.createElement('div')
  					divDom.innerHTML = r;
  					document.body.appendChild(divDom)

  					let testForm = document.getElementsByName('punchout_form')
  					testForm[0].dispatchEvent(new Event('submit'))
  					testForm[0].submit()
  					document.body.removeChild(testForm[0])

  				}
  			//	window.location.href = r;
  				// #endif
  				// #ifdef APP-PLUS
  				uni.requestPayment({
  					provider: 'alipay',
  					orderInfo: r, //微信、支付宝订单数据
  					success: function () {
  						mHelper.toast('充值成功');
  						mRouter.redirectTo({route});
  					},
  					fail: function (err) {

  						mHelper.toast(err);
  					}
  				});
  				// #endif
  			});
  	},
};
